<template>
  <el-dialog :visible.sync="visible" title="人员信息" @close="closeDialog">
    <el-form :model="form" ref="form" label-width="120px" :rules="rules">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="账号" prop="account">
        <el-input v-model="form.account"></el-input>
      </el-form-item>
      <el-form-item label="职位" prop="position">
        <el-input v-model="form.position"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="地区id" prop="region_id">
        <el-input v-model="form.region_id"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import axios from 'axios';
export default {
  name: 'PersonDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    person: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {
        name: '',
        account: '',
        position: '',
        phone: '',
        email: '',
        region_id: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        position: [
          { required: true, message: '请输入职位', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        region_id: [
          { required: true, message: '请输入地区id', trigger: 'blur' }
        ]
      }
    };
  },
  watch: {
    person: {
      handler(newVal) {
        if (this.isEdit && newVal) {
          this.form = { ...newVal };
          axios.post('/api/person/searchbyname', newVal.name, {
            headers: {
              'Content-Type': 'text/plain'
            }
          })
            .then(res => {
              console.log(res.data)
              // 使用 Vue.set 确保响应式更新
              this.$set(this.form, 'account', res.data.account);
              this.$set(this.form, 'email', res.data.email);
              this.$set(this.form, 'position', res.data.position);
              this.$set(this.form, 'phone', res.data.phone);
              this.$set(this.form, 'region_id', res.data.region_id);
            })
            .catch(err => {
              console.error('Error:', err);
            });
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    closeDialog() {
      this.$emit('close');
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            axios.post('/api/person/update', this.form)
              .then(() => {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
                this.$emit('refresh');
                this.closeDialog();
              })
              .catch(err => {
                console.error('Error:', err);
              });
          } else {
            this.checkIfExists().then(exists => {
              if (exists) {
                this.$message.error('该账号已经存在');
              } else {
                axios.post('/api/person/personadd', this.form)
                  .then(() => {
                    this.$message({
                      message: '新增成功',
                      type: 'success'
                    });
                    this.$emit('refresh');
                    this.closeDialog();
                  })
                  .catch(err => {
                    console.error('Error:', err);
                  });
              }
            });
          }
        } else {
          this.$message.error('请填写所有必填项');
        }
      });
    },
    checkIfExists() {
      return axios.post('/api/person/search', { account: this.form.account })
        .then(res => res.data.success)
        .catch(err => {
          console.error('Error:', err);
          return false;
        });
    }
  }
};
</script>

<style scoped>
/* 样式 */
</style>
